package com.jindy.module.oaClockApproval.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oaDepartApproval.domain.SyOaDepart;
import com.jindy.module.oaDepartApproval.service.impl.SyOaDepartServiceImpl;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.oaClockApproval.mapper.SyOaClockMapper;
import com.jindy.module.oaClockApproval.domain.SyOaClock;
import com.jindy.module.oaClockApproval.service.ISyOaClockService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 补卡审批Service业务层处理
 * 
 * @author jindy
 * @date 2023-06-05
 */
@Service
public class SyOaClockServiceImpl implements ISyOaClockService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyOaClockServiceImpl.class);

    @Autowired
    private SyOaClockMapper syOaClockMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;

    /**
     * 查询补卡审批
     * 
     * @param id 补卡审批主键
     * @return 补卡审批
     */
    @Override
    public SyOaClock selectSyOaClockById(Long id)
    {
        return syOaClockMapper.selectSyOaClockById(id);
    }

    /**
     * 查询补卡审批列表
     * 
     * @param syOaClock 补卡审批
     * @return 补卡审批
     */
    @Override
    public List<SyOaClock> selectSyOaClockList(SyOaClock syOaClock)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            syOaClock.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOaClock> list = syOaClockMapper.selectSyOaClockList(syOaClock);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    /**
     * 新增补卡审批
     * 
     * @param syOaClock 补卡审批
     * @return 结果
     */
    @Override
    public int insertSyOaClock(SyOaClock syOaClock)
    {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("BKSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增补卡审批-获取补卡单号失败");
        }
        //获取申请人信息
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        syOaClock.setApplyUserId(userId.toString());
        syOaClock.setApplyUserName(SecurityUtils.getLoginUser().getUser().getUserName());

        //获取申请时间
        syOaClock.setApplyTime(DateUtils.getNowDate());

        syOaClock.setSerialNum(serialNum);
        syOaClock.setBusinessStatus(Constants.DRAFT);
        syOaClock.setCreateTime(DateUtils.getNowDate());
        iSyTableRecordTService.saveEntityAndTable(syOaClock,serialNum);
        return syOaClockMapper.insertSyOaClock(syOaClock);
//        syOaClock.setCreateTime(DateUtils.getNowDate());
//        return syOaClockMapper.insertSyOaClock(syOaClock);
    }

    /**
     * 修改补卡审批
     * 
     * @param syOaClock 补卡审批
     * @return 结果
     */
    @Override
    public int updateSyOaClock(SyOaClock syOaClock)
    {
        syOaClock.setUpdateTime(DateUtils.getNowDate());
        return syOaClockMapper.updateSyOaClock(syOaClock);
    }

    /**
     * 批量删除补卡审批
     * 
     * @param ids 需要删除的补卡审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaClockByIds(Long[] ids)
    {
        return syOaClockMapper.deleteSyOaClockByIds(ids);
    }

    /**
     * 删除补卡审批信息
     * 
     * @param id 补卡审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaClockById(Long id)
    {
        return syOaClockMapper.deleteSyOaClockById(id);
    }

    /**
     * 提交申请
     *
     * @param syOaClock
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOaClock syOaClock) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(syOaClock);
        // 启动流程
        processService.submitApply(syOaClock, "clock", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("BKSP", syOaClock.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(syOaClock, variables);
        // 通知审批人
        sendApproveMessage(longs);
        syOaClock.setBusinessStatus(Constants.APPROVE);
        updateSyOaClock(syOaClock);
    }

    /**
     * 新增审批记录
     * @param syOaClock
     * @param map
     * @return
     */
    private List<Long> addApprovalRecord(SyOaClock syOaClock, Map<String, Object> map) {
        List<Long> list = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syOaClock);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syOaClock.getApplyUserId()));
        firstApprovalRecord.setApproverName(syOaClock.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        //主管审批
        sequence++;
        //  第一审批人
        ApprovalRecord secondApprovalRecord = getApprovalRecord(syOaClock);
        secondApprovalRecord.setSequence(sequence);
        secondApprovalRecord.setApprovalStatus(Constants.APPROVE);
        String deptleaderId=map.get("deptleaderId").toString();
        secondApprovalRecord.setApproverId(Long.parseLong(deptleaderId));
        secondApprovalRecord.setApproverName((String) map.get("deptleader"));
        approvalRecordMapper.insertApprovalRecord(secondApprovalRecord);
        list.add(Long.parseLong(deptleaderId));

        return list;
    }

    /**
     * 获取审批记录对象
     *
     * @param syOaClock
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOaClock syOaClock) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syOaClock.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syOaClock.getApplyUserId()));
        approvalRecord.setOrderId(syOaClock.getId());
        approvalRecord.setUserName(syOaClock.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syOaClock.getApplyUserName());
        approvalRecord.setCreateBy(syOaClock.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 逻辑流初始化
     *
     * @param syOaClock
     * @return
     */
    public Map<String, Object> createVariables(SyOaClock syOaClock) {
        Map<String, Object> var = new HashMap<>(500);
        List<SysUserRoleDeptInfo> userList = sysUserService.selectUsersByUserName(syOaClock.getApplyUserName());

        if (CollectionUtils.isEmpty(userList)) {
            throw new BaseException("外出审批-判断是否为直接主管集合为空");
        }

        var.put("deptleader",userList.get(0).getLeader());
        var.put("deptleaderId",userList.get(0).getLeaderId());

        return var;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("离职审批审批人推送通知失败",e);
        }
    }

    /**
     * 申请人当月申请补卡次数查询
     * @param applyUserId
     */
    public int clockTimes(String applyUserId){
        List<SyOaClock> syOaClockList=(syOaClockMapper.selectSyOaClockByApplyUserId(applyUserId));
        if(syOaClockList.size()>0){
            return syOaClockList.size();
        }
        return 0;
    }

    /**
     * 申请人当月申请补卡成功次数查询
     * @param syOaClock
     */
    public int clockTimesComplete(SyOaClock syOaClock){
        int times=0;
        List<SyOaClock> syOaClockList=(syOaClockMapper.selectSyOaClockByApplyUserId(syOaClock.getApplyUserId()));
        if(syOaClockList.size()>0){
            try {
                processService.richProcessField(syOaClock);
            }catch (Exception e){
                throw new BaseException("外出审批-判断是否为直接主管集合为空");
            }
            if(syOaClock.getTaskName().equals("已结束")){
                times++;
            }

        }
        return times;
    }
}
